
import { setAuthority, getAuthority } from '@/custom/authority'
import { routerRedux } from 'dva/router'
import { getUser } from '@/services/api'

export default {

  namespace: 'global',

  state: {
    status: 0,
    user: null,
    token: null,
    collapsed: false
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
      let { token } = getAuthority()
      if (token) {
        dispatch({ type: 'changeUser', payload: { token: token } })
      }

    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {  // eslint-disable-line
      yield put({ type: 'save' })
    },
    *getCurrentUser({}, { call, put, select }) {
      const token = yield select(state => {
        return state.global.token
      })
      const resp = yield call(getUser, { token })
      if (resp instanceof Error) {
        yield put(routerRedux.push('/login'))
        setAuthority('')
        yield put({ type: 'changeUser', payload: { token: null } })
        return
      }
      const { user } = resp
      yield put({
        type: 'changeUser',
        payload: { token, user }
      })
    }
  },

  reducers: {
    changeUser(state, { payload: { user, token } }) {
      return { ...state, user: user, token: token }
    },
    toggleCollapsed(state, { payload }) {
      return { ...state, collapsed: payload.collapsed  }
    }
  },

};
